// import LocalforageHelp from '@/utils/LocalforageHelp'
// const lfh = LocalforageHelp()

/**
 * @description localStorage统一管理
 * @list
 *      storage.set(key, value, expired)    - 设置 storage
 *      storage.get(key)                    - 获取 storage
 *      storage.remove(key)                 - 删除 storage
 *      storage.clearExpired()              - 清除已过期的 storage
 * @whyDo
 *      用户 localStorage 本地存储大小是有限的，如果不限制使用，没有合理管理，将造成不可预期的问题
 * @whatDo
 *      统一管理项目 localStorage 使用，增加过期时间，页面加载时自动清除过期的存储
 */

const localStorageKey = "project_storage_info";

const dataT = 1000*60*60*24 // 一天的毫秒

class Storage {
  constructor() {
    this.cache = {};
  }
  // new Date().getTime()
  set(key, value, expiredTime = 1) {
    // expiredTime 单位为天
    this.cache = this.get();
    if (this.cache[key]) delete this.cache[key];
    const info = {
      value,
      newExpired: Date.now(),
      expired: expiredTime * dataT
    };
    this.cache[key] = info;
    localStorage.setItem(localStorageKey, JSON.stringify(this.cache));
  }
  get(key) {
    const str = localStorage.getItem(localStorageKey);
    this.cache = str ? JSON.parse(str) : {};
    if (key) {
      const tempCheck = this.cache[key]
      // if (tempCheck) {
      //   return tempCheck.value;
      // }
      if (tempCheck && this.check(tempCheck.newExpired, tempCheck.expired,key)) {
        return tempCheck.value;
      }
      return "";
    }
    return this.cache;
  }
  check(newExpired,expired,key){
    let res= true
    const temp =  Date.now()
    if(temp - newExpired >= expired){
      res= false
      this.remove(key)
    }
    return res
  }
  remove(key) {
    // 此处可根据实际情况提供全部删除方法，个人感觉有一定风险
    if (!key) throw new Error("localStorage 删除操作必须传入对应的 key 值！！！");
    this.cache = this.get();
    delete this.cache[key];
    localStorage.setItem(localStorageKey, JSON.stringify(this.cache));
  }
  clearExpired() {
    const cache_ = this.get();
    if (!Object.keys(cache_).length) return;
    for (const key in cache_) {
      if (cache_[key].expired <  Date.now()-cache_[key].newExpired) {
        delete cache_[key];
      }
    }
    localStorage.setItem(localStorageKey, JSON.stringify(cache_));
  }
}

export default new Storage();
